package com.tanhua.dubbo.api;

import com.tanhua.domain.sound.Sound;

import com.tanhua.dubbo.utils.IdSequeue;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

/**
 * @author To my left is the dog
 * @date 2021/2/28 15:49
 */
@Service
public class SoundApiImpl implements SoundApi {
    @Autowired
    private IdSequeue idSequeue;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveSound(Sound sound) {
        sound.setId(new ObjectId());
        sound.setSid(idSequeue.getNextId("sound"));
        sound.setCreated(System.currentTimeMillis());
        mongoTemplate.save(sound);
    }


    /*MongoDB的数组属性很好地管理了RDB的多对多表中的数据，使得查询效率较高。有时只需查询第1个元素，来看代码：
    db.your_collection.find({},{"array_field" : {"$slice":1}})
    在Spring-data-mongodb中这样实现：
    Query query = new Query();
    query.fields().slice("array_field", 1);
    mongoTemplate.find(query, YourCollectionEntity.class);*/
    @Override
    public Sound findById(Long userIdRandom) {
        Query query = new Query(Criteria.where("userId").is(userIdRandom));
        query.with(Sort.by(Sort.Order.desc("created"))).fields().slice("userId",1);
        return mongoTemplate.findOne(query,Sound.class);
    }

    @Override
    public void remove(Long userIdRandom) {
        Query query = new Query(Criteria.where("userId").is(userIdRandom));
        query.with(Sort.by(Sort.Direction.DESC,"created")); // 根据发送的时间降序
        query.fields().slice("userId",1); // 只查询第一条数据
        mongoTemplate.remove(query, Sound.class);
    }
}
